package com.springcloud.zull.interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import utils.ResponseBean;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wfh
 */
@ControllerAdvice
public class PackResult implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        return ResponseBeanIntercepter.REQUEST_FLAG.equals(request.getAttribute(ResponseBeanIntercepter.REQUEST_FLAG));
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (o instanceof ResponseBean) {
            return o;
        } else {

            if (o instanceof String) {
                String str = (String) o;
                if (str.contains("\"code\":") && str.contains("\"message\":") && str.contains("\"data\":")) {
                    return o;
                }
                return JSON.toJSONString(ResponseBean.secucess(o));
            }
        }
        return ResponseBean.secucess(o);
    }
}
